<template>
    <div class="network-component-dialog-modal-wrapper">
        <el-dialog :model-value="props.value" :title="dialog.title" :width="dialog.width" destroy-on-close>
            <el-form ref="ruleFormRef" :model="formData" :rules="ruleForm" label-width="120px">
                <div class="form-item-box-one">
                    <div>
                        <el-form-item label="网络组件名称" prop="componentName">
                            <el-input
                                v-model="formData.componentName"
                                @input="value => (formData.componentName = value.trim())"
                                placeholder="请输入网络组件名称"
                                :disabled="props.readonly"
                                maxlength="50"
                            />
                        </el-form-item>
                        <el-form-item label="所属协议" prop="protocolType">
                            <el-select v-model="formData.protocolType" :disabled="props.readonly || true">
                                <el-option
                                    v-for="(value, key) in [{ label: 'MQTT', value: 'mqtt' }]"
                                    :label="value.label"
                                    :key="value.value"
                                    :value="value.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="管理端端口" prop="serverPort">
                            <el-input-number
                                v-model="formData.serverPort"
                                placeholder="请输入管理端端口"
                                :disabled="props.readonly"
                                :min="0"
                                :max="65535"
                                style="width: 100%"
                                controls-position="right"
                                align="left"
                            />
                        </el-form-item>
                        <el-form-item label="管理端用户名" prop="serverUsername">
                            <el-input
                                v-model="formData.serverUsername"
                                @input="value => (formData.serverUsername = value.trim())"
                                placeholder="请输入管理端用户名"
                                :disabled="props.readonly"
                                maxlength="50"
                            />
                        </el-form-item>
                        <el-form-item label="服务端用户名" prop="username">
                            <el-input
                                v-model="formData.username"
                                @input="value => (formData.username = value.trim())"
                                placeholder="请输入服务端用户名"
                                :disabled="props.readonly"
                                maxlength="50"
                            />
                        </el-form-item>
                    </div>
                    <div>
                        <el-form-item label="标识符" prop="componentNo">
                            <el-input
                                v-model="formData.componentNo"
                                @input="value => (formData.componentNo = value.trim())"
                                placeholder="系统自动生成"
                                disabled
                            />
                        </el-form-item>
                        <el-form-item label="服务地址" prop="address">
                            <el-input
                                v-model="formData.address"
                                @input="value => (formData.address = value.trim())"
                                placeholder="请输入服务地址"
                                :disabled="props.readonly"
                                maxlength="50"
                            />
                        </el-form-item>
                        <el-form-item label="服务端端口" prop="port">
                            <el-input-number
                                v-model="formData.port"
                                placeholder="请输入服务端端口"
                                :disabled="props.readonly"
                                :min="0"
                                :max="65535"
                                style="width: 100%"
                                controls-position="right"
                                align="left"
                            />
                        </el-form-item>
                        <el-form-item label="管理端密码" prop="serverPassword">
                            <el-input
                                v-model="formData.serverPassword"
                                @input="value => (formData.serverPassword = value.trim())"
                                placeholder="请输入管理端密码"
                                type="password"
                                show-password
                                :disabled="props.readonly"
                                maxlength="50"
                            />
                        </el-form-item>
                        <el-form-item label="服务端密码" prop="password">
                            <el-input
                                v-model="formData.password"
                                @input="value => (formData.password = value.trim())"
                                placeholder="请输入服务端密码"
                                type="password"
                                show-password
                                :disabled="props.readonly"
                                maxlength="50"
                            />
                        </el-form-item>
                    </div>
                </div>
                <el-form-item label="描述" prop="componentDesc">
                    <el-input
                        v-model="formData.componentDesc"
                        maxlength="200"
                        show-word-limit
                        type="textarea"
                        placeholder="请输入描述"
                        :disabled="props.readonly"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="props.close">取消</el-button>
                    <el-button type="primary" @click="submitForm" :loading="loading">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus';
import type { NetworkComponentVO } from '@great/services';
import { runNetworkComponentService } from '@great/services';
import { reactive, ref } from 'vue';
import type { PopupBoxProps } from '@great/utils';
import { useRequest } from 'vue-request';
import { ScriptType } from '@/utils/constant';

const { proxy } = getCurrentInstance() as any;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

interface IProps extends PopupBoxProps {
    row?: NetworkComponentVO;
    getList?: () => Promise<void>;
    readonly?: boolean;
}
const props = defineProps<IProps>();

interface Dialog {
    title: string;
    width: number;
    detail?: NetworkComponentVO;
}
const dialog = reactive<Dialog>({
    title: '新建网络组件',
    width: 900,
    detail: undefined
});

const formData = reactive<NetworkComponentVO>({
    componentName: '',
    componentNo: '',
    protocolType: 'mqtt',
    address: '0.0.0.0',
    port: '',
    username: '',
    password: '',
    serverUsername: '',
    serverPassword: '',
    serverPort: '',
    componentDesc: ''
});

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<FormRules>({
    componentName: [{ required: true, message: '请输入网络组件名称', trigger: ['blur', 'change'] }],
    protocolType: [{ required: true, message: '请选择所属协议', trigger: ['blur', 'change'] }],
    address: [
        { required: true, message: '请输入服务地址', trigger: ['blur', 'change'] },
        {
            validator: (rule, value, callback) => {
                // 符合ip地址的正则表达式
                const ipRegex =
                    /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
                if (!ipRegex.test(value)) {
                    return callback(new Error('必须符合IP地址格式(例如:192.168.0.1)'));
                }
                callback();
            },
            trigger: ['blur', 'change']
        }
    ],
    port: [{ required: true, message: '请输入服务端端口', trigger: ['blur', 'change'] }],
    serverPort: [{ required: true, message: '请输入管理端端口', trigger: ['blur', 'change'] }],
    username: [{ required: true, message: '请输入服务端用户名', trigger: ['blur', 'change'] }],
    password: [{ required: true, message: '请输入服务端密码', trigger: ['blur', 'change'] }],
    serverUsername: [{ required: true, message: '请输入管理端用户名', trigger: ['blur', 'change'] }],
    serverPassword: [{ required: true, message: '请输入管理端密码', trigger: ['blur', 'change'] }]
});

// 是否为编辑
const isEdit = (par?: boolean): boolean => {
    if (par === undefined) {
        return dialog.title.includes('修改');
    } else {
        return dialog.title.includes('修改') && par;
    }
};

// 提交接口请求
const { run, loading } = useRequest(
    () => {
        return runNetworkComponentService[isEdit() ? 'updateNetWorkComponent' : 'addNetWorkComponent'](formData);
    },
    {
        manual: true,
        onSuccess(res) {
            ElNotification({
                title: isEdit() ? '修改成功！' : '创建成功！',
                type: 'success'
            });
            closeDialog();
        }
    }
);
// 表单提交
const submitForm = () => {
    if (props.readonly) {
        closeDialog();
        return;
    }
    ruleFormRef.value?.validate(valid => {
        valid && run();
    });
};

//关闭弹框
const closeDialog = () => {
    props.close();
    if (props.getList) props.getList();
};

// 打开弹框
const openDialog = () => {
    if (props.row) {
        if (props.readonly) {
            dialog.title = '查看网络组件';
        } else {
            dialog.title = '修改网络组件';
        }
        dialog.detail = JSON.parse(JSON.stringify(props.row));
        formData.id = props.row.id;
        Object.keys(formData).forEach(key => {
            formData[key] = (props.row as NetworkComponentVO)[key];
        });
    }
};

const init = () => {
    openDialog();
};
init();
</script>
<style scoped lang="scss">
.network-component-dialog-modal-wrapper {
    .el-form {
        .form-item-box-one {
            display: flex;
            justify-content: space-between;
            > div {
                width: calc((100% - 10px) / 2);
            }
        }
    }
}
</style>
